<template>
  <div id="tpr-list" class="card bg-transparent">
    <div class="card-header bg-info text-white">出票TSL/TPR数据</div>

    <div class="card-body">
      <form class="row row-cols-lg-auto align-items-center">
        <div class="col-1">
          <my-date-picker
            :id="'beginDate'"
            :class="'form-control m-1'"
            :placeholder="'开始日期'"
            v-model="beginDate"
          ></my-date-picker>
        </div>
        <div class="col-1">
          <my-date-picker
            :id="'endDate'"
            :class="'form-control'"
            :placeholder="'截止日期'"
            v-model="endDate"
          ></my-date-picker>
        </div>
        <div class="col-1">
          <input
            class="form-control"
            type="text"
            placeholder="eterm用户名"
            size="10"
            v-model="etermUsername"
          />
        </div>
        <div class="col">
          <input
            class="form-control"
            type="text"
            placeholder="设备号"
            size="4"
            v-model="deviceId"
          />
        </div>
        <div class="col-1">
          <input
            class="form-control"
            type="text"
            placeholder="票号"
            size="12"
            v-model.trim="ticketNo"
          />
        </div>
        <label>客票类型</label>
        <div class="col-1">
          <select class="form-select" v-model.number="ticketStatus">
            <option value="-1">所有</option>
            <option value="0">正常票</option>
            <option value="1">改签</option>
            <option value="4">退票</option>
          </select>
        </div>
        <label>匹配状态</label>
        <div class="col-1">
          <select class="form-select" v-model.number="checkStatus">
            <option value="-1">所有</option>
            <option value="0">待匹配</option>
            <option value="2">已匹配</option>
          </select>
        </div>
        <label>每页记录数</label>
        <div class="col-1">
          <select class="form-select" v-model.number="sc.pageSize">
            <option value="10">10</option>
            <option value="25">25</option>
            <option value="50">50</option>
            <option value="500">500</option>
            <option value="5000">5000</option>
          </select>
        </div>
        <div class="col">
          <button
            type="button"
            class="btn btn-success me-2"
            @click.stop="search()"
          >
            查找
          </button>
          <button
            type="button"
            class="btn btn-info btn-sm"
            @click.stop="reset()"
          >
            重置
          </button>
        </div>
        <div class="col">
          <button
            type="button"
            class="btn btn-sm btn-success ms-2 float-end d-none"
            @click.stop="importExcel()"
          >
            导入Excel
          </button>
          <button
            type="button"
            class="btn btn-sm btn-primary ms-2 float-end d-none"
            @click.stop="importTprContent()"
          >
            导入TPR
          </button>

          <button
            type="button"
            class="btn btn-sm btn-secondary ms-2 float-end"
            @click.stop="downloadTpr()"
          >
            下载
          </button>
        </div>
      </form>
    </div>
    <div class="card-body p-1">
      <my-pagination
        :row-count="sc.rowCount"
        :page-total="sc.pageTotal"
        :page-no="sc.pageNo"
        @next-page="nextPage"
        @prev-page="prevPage"
        @direct-page="directPage"
      ></my-pagination>
    </div>
    <table class="table table-sm table-striped table-hover">
      <thead>
        <tr>
          <th>出票日期</th>
          <th class="hidden-sm-down">设备号</th>
          <th>票号</th>
          <th>编码</th>
          <th>出发</th>
          <th>到达</th>
          <th class="text-end">价格</th>
          <th class="text-end">航段奖励</th>
          <th class="text-end">底价（不含税)</th>
          <th class="text-end">税</th>
          <th class="text-end">底价（含税）</th>
          <th>生成时间</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr v-if="ticketStatus === 0">
          <td colspan="6">小计</td>
          <td class="text-end">{{ totalInfo.normalFareAmount }}</td>
          <td class="text-end">{{ totalInfo.normalCommitAmount }}</td>
          <td class="text-end">{{ totalInfo.carriersAmount }}</td>
          <td class="text-end">{{ totalInfo.normalTaxAmount }}</td>
          <td class="text-end"></td>
          <td class="text-end"></td>
          <td class="">已匹配 {{ totalInfo.normalMatchedCount }} 个</td>
        </tr>
        <tr v-if="ticketStatus === 4">
          <td colspan="6">小计</td>
          <td class="text-end">{{ totalInfo.netRefundAmount }}</td>
          <td class="text-end">{{ totalInfo.refundCommit }}</td>
          <td class="text-end"></td>
          <td class="text-end">{{ totalInfo.refundTaxAmount }}</td>
          <td class="text-end"></td>
          <td class="text-end"></td>
          <td class="">已匹配 {{ totalInfo.refundMatchedCount }} 个</td>
        </tr>
        <tr v-for="flight in dataList" :key="flight.id">
          <td>
            <small>{{ flight.sellDate }}</small>
          </td>
          <td class="hidden-sm-down">
            <small>{{ flight.deviceId }}</small>
          </td>
          <td>
            {{ flight.ticketNo }}
            <span class="text-muted" v-if="flight.ticketStatus === 1"
              >改签</span
            >
            <span class="text-muted" v-if="flight.ticketStatus === 4"
              >退票</span
            >
            <span class="text-muted" v-if="flight.ticketStatus === 16">废</span>
            {{ flight.conjTag }}
          </td>
          <td>
            {{ flight.pnrNo }}
          </td>
          <td>{{ flight.orig }}</td>
          <td>{{ flight.dest }}</td>
          <td class="text-end">{{ flight.price }}</td>
          <td class="text-end">{{ flight.commission }}</td>
          <td class="text-end">{{ flight.bottomPrice - flight.tax }}</td>
          <td class="text-end">{{ flight.tax }}</td>
          <td class="text-end">{{ flight.bottomPrice }}</td>
          <td>{{ flight.createTime }}</td>
          <td>
            <span v-if="flight.checkStatus === 2"
              >已匹配(<router-link
                :to="`/bill/detail/0?billNum=` + flight.billNum"
                target="_blank"
                >{{ flight.billNum }}</router-link
              >)</span
            >
          </td>
        </tr>
      </tbody>
    </table>

    <div class="card-footer">
      <my-pagination
        :row-count="sc.rowCount"
        :page-total="sc.pageTotal"
        :page-no="sc.pageNo"
        @next-page="nextPage"
        @prev-page="prevPage"
        @direct-page="directPage"
      ></my-pagination>
    </div>

    <!-- New  Modal -->
    <div
      class="modal"
      id="modalTpr"
      tabindex="-1"
      role="dialog"
      aria-labelledby="myModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title" id="myModalLabel">导入tpr指令结果</h4>
            <button type="button" class="close" data-dismiss="modal">
              <span aria-hidden="true">&times;</span
              ><span class="sr-only">Close</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="row">
              <label class="col-3 text-end">导入方式</label>
              <div class="col-6">
                <div class="form-check form-check-inline">
                  <input
                    class="form-check-input"
                    type="radio"
                    value="0"
                    v-model.number="tprMode"
                  />
                  <label class="form-check-label">TPR内容</label>
                </div>
                <div class="form-check form-check-inline">
                  <input
                    class="form-check-input"
                    type="radio"
                    value="1"
                    v-model.number="tprMode"
                  />
                  <label class="form-check-label">接口导入</label>
                </div>
              </div>
            </div>
            <div class="col-1" v-if="tprMode === 0">
              <label for="exampleFormControlTextarea1">tpr指令结果</label>
              <textarea
                class="form-control"
                id="exampleFormControlTextarea1"
                rows="10"
                v-model.trim="tprContent"
              ></textarea>
              <span class="text-muted small">请将tpr指令结果完全复制</span>
            </div>
            <div class="col-1" v-if="tprMode === 1">
              <label for="exampleFormControlTextarea1">tpr日期</label>
              <my-date-picker
                id="deliveryDate"
                v-model.trim="tprDate"
              ></my-date-picker>
              <span class="text-muted small"></span>
            </div>
            <div class="col-1" v-if="tprMode === 1">
              <label>打票机</label>
              <input class="form-control" v-model.number="printerId" />
              <span class="text-muted small"></span>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              取消
            </button>
            <button
              type="button"
              class="btn btn-primary"
              @click.stop="saveTprContent()"
            >
              保存
            </button>
          </div>
        </div>
      </div>
    </div>
    <div
      class="modal"
      id="modalExcel"
      tabindex="-1"
      role="dialog"
      aria-labelledby="myModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title" id="myModalLabel">
              上传Excel文件导入机票数据
            </h4>
            <button type="button" class="close" data-dismiss="modal">
              <span aria-hidden="true">&times;</span>
              <span class="sr-only">Close</span>
            </button>
          </div>
          <div class="modal-body">
            <form
              id="uploadFileForm"
              method="post"
              enctype="multipart/form-data"
            >
              <input type="hidden" name="fileContentType" value="100" />
              <div class="col-1">
                <label class="control-label"> 供应商 </label>
                <div>
                  <select class="form-select" name="supplierId">
                    <option value="0">请选择供应商</option>
                    <template v-for="info in suppliers">
                      <option :value="info.id" :key="info.id">
                        {{ info.name }}
                      </option>
                    </template>
                  </select>
                </div>
              </div>
              <div class="col-1">
                <label class="control-label"> Excel格式 </label>
                <div>
                  <select class="form-select" name="formatNo">
                    <option value="1">
                      格式一
                      (出票日期、开始票号、截止票号、票数、支付金额、支付备注)
                    </option>
                    <option value="2">
                      格式二 (票号、乘机人、PNR、航班号、支付金额、出票日期)
                    </option>
                  </select>
                </div>
                <span class="text-muted small">
                  格式一（六列）：出票日期、开始票号、截止票号、票数、支付金额、支付备注；数据从第二行开始）<br />
                  格式二（六列）：票号、乘机人、PNR、航班号、支付金额、出票日期；数据从第二行开始）<br />
                </span>
              </div>
              <div class="col-1">
                <label>选择需要上传的文件</label>
                <input
                  type="file"
                  class=""
                  name="upfile"
                  id="inputFileName"
                />
                <span class="text-muted small">
                  文件名请不要有中文或全角字符，请使用字母或数字命名文件名。
                </span>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-default btn-sm"
              data-dismiss="modal"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-primary btn-lg ms-2"
              @click.stop="uploadExcel()"
              :disabled="uploading"
            >
              <template v-if="uploading"> 上传中... </template>
              <template v-else> 开始上传 </template>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import MyPagination from "@/components/my-pagination.vue";
import MyDatePicker from "@/components/my-datepicker.vue";
import { searchTpr, saveTprContent } from "@/api/flight";
import { searchSuppliers } from "@/api/basic-data";
import { APP_FLIGHT_PATH } from "@/common/common.js";
import $ from "jquery";

export default {
  name: "TprList",
  components: {
    MyPagination,
    MyDatePicker,
  },
  data() {
    return {
      dataList: [],
      sc: {
        rowCount: 0,
        pageNo: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      beginDate: "",
      endDate: "",
      deviceId: "",
      ticketNo: "",
      ticketStatus: -1,
      checkStatus: -1,
      etermUsername: "",

      tprMode: 0,
      tprContent: "",
      tprDate: "",
      printerId: 1,
      suppliers: [],

      uploading: false,

      totalInfo: {
        normalFareAmount: 0,
        carriersAmount: 0,
        normalTaxAmount: 0,
        normalCommitAmount: 0,
        normalMatchedCount: 0,

        netRefundAmount: 0,
        deductionAmount: 0,
        refundTaxAmount: 0,
        refundCommitAmount: 0,
        refundMatchedCount: 0,
      },
    };
  },
  mounted: function () {
    if (window.matchMedia("(max-width: 576px)").matches) {
      // console.log(this.$router.to)
      this.$router.replace("/h5/tools/tprs");
    } else {
      this.search();
    }
  },
  methods: {
    back: function () {
      this.$router.go(-1);
    },
    showErrMsg: function (msg, msgType) {
      this.$store.dispatch("showAlertMsg", {
        errMsg: msg,
        errMsgType: msgType,
      });
    },
    showLoading: function (loadingText) {
      this.$store.commit("showLoading", {
        loading: true,
        loadingText: loadingText,
      });
    },
    hideLoading: function () {
      this.$store.commit("showLoading", {
        loading: false,
      });
    },
    search: function () {
      let deviceId = this.deviceId;
      if (deviceId === "") {
        deviceId = 0;
      }

      let beginDate = this.beginDate;
      if (beginDate === "") {
        beginDate = null;
      }

      let endDate = this.endDate;
      if (endDate === "") {
        endDate = null;
      }

      let params = {
        beginDate: beginDate,
        endDate: endDate,
        device: deviceId,
        ticketNo: this.ticketNo,
        ticketStatus: this.ticketStatus,
        checkStatus: this.checkStatus,
        etermUsername: this.etermUsername,
        pageSize: this.sc.pageSize,
        pageNo: this.sc.pageNo,
      };

      this.showLoading();

      searchTpr(
        params,
        (jsonResult) => {
          this.dataList = jsonResult.dataList;
          this.sc = jsonResult.page;
          this.calcTotal();
        },
        () => {
          this.hideLoading();
        }
      );
    },
    reset: function () {
      this.beginDate = "";
      this.endDate = "";
      this.deviceId = "";
      this.ticketNo = "";
      this.etermUsername = "";
    },
    prevPage: function () {
      this.sc.pageNo = this.sc.pageNo - 1;
      if (this.sc.pageNo < 1) this.sc.pageNo = 1;
      this.search();
    },
    nextPage: function () {
      this.sc.pageNo = this.sc.pageNo + 1;
      this.search();
    },
    directPage: function (pageNo) {
      this.sc.pageNo = pageNo;
      this.search();
    },
    showAbbr: function (val) {
      if (val !== null && val.length > 10) {
        return val.substring(0, 10) + "...";
      } else {
        return val;
      }
    },
    showStatus: function (val) {
      switch (val) {
        case 0:
          return "";
        case 4:
          return "已退票";
        default:
          return val;
      }
    },
    calcTotal: function () {
      this.resetTotal();
      this.dataList.forEach((item, index, arr) => {
        if (item.ticketStatus === 0 || item.ticketStatus === 1) {
          //出票、改签都算正常票
          this.totalInfo.normalFareAmount += item.price;
          this.totalInfo.normalTaxAmount += item.tax;
          this.totalInfo.normalCommitAmount += item.commission;
          this.totalInfo.carriersAmount += item.price - item.commission;
          if (item.checkStatus === 2) {
            this.totalInfo.normalMatchedCount += 1;
          }
        } else if (item.ticketStatus === 4) {
          //退票
          this.totalInfo.netRefundAmount += item.price;
          this.totalInfo.deductionAmount += item.tax;
          this.totalInfo.refundTaxAmount += item.tax;
          this.totalInfo.refundCommit += item.commission;
          if (item.checkStatus === 2) {
            this.totalInfo.refundMatchedCount += 1;
          }
        }
      });
    },
    resetTotal: function () {
      this.totalInfo.normalFareAmount = 0;
      this.totalInfo.normalTaxAmount = 0;
      this.totalInfo.normalCommitAmount = 0;
      this.totalInfo.carriersAmount = 0;
      this.totalInfo.normalMatchedCount = 0;

      this.totalInfo.netRefundAmount = 0;
      this.totalInfo.deductionAmount = 0;
      this.totalInfo.refundTaxAmount = 0;
      this.totalInfo.refundCommit = 0;
      this.totalInfo.refundMatchedCount = 0;
    },
    importTprContent: function () {
      this.tprContent = "";
      $("#modalTpr").modal();
    },
    importExcel: function () {
      this.searchSuppliers();
      $("#modalExcel").modal();
    },
    saveTprContent: function () {
      const params = {
        tprContent: this.tprContent,
        tprDate: this.tprDate,
        deviceId: this.printerId,
      };
      saveTprContent(params, (v) => {
        if (v.status === "OK") {
          $("#modalTpr").modal("hide");
          this.search();
        } else {
          this.showErrMsg("保存失败: " + v.errmsg, "danger");
        }
      });
    },
    searchSuppliers: function () {
      if (this.suppliers.length > 0) return;

      const params = {
        "sc.pageNo": 1,
        "sc.pageSize": 50,
      };

      searchSuppliers(params, (jsonResult) => {
        this.suppliers = jsonResult.dataList;
      });
    },
    uploadExcel: function () {
      const filename = $("#inputFileName").val();
      if (filename.length === 0) {
        this.showErrMsg("请选择需要导入的EXCEL文件");
        return;
      }

      this.uploading = true;
      const self = this;

      // showLoading();
      var formData = new window.FormData($("#uploadFileForm")[0]);
      $.ajax({
        url: APP_FLIGHT_PATH + "/upload/excel",
        type: "POST",
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (jsonResult) {
          if (jsonResult.status !== "OK") {
            self.showErrMsg(jsonResult.errmsg);
          } else {
            self.showErrMsg("上传成功, " + jsonResult.desc);
            $("#inputFileName").val("");
            $("#modalExcel").modal("hide");
          }
        },
        complete: function () {
          self.uploading = false;
        },
      });
    },
    downloadTpr: function () {
      const params =
        "endDate=" +
        this.endDate +
        "&beginDate=" +
        this.beginDate +
        "&etermUsername=" +
        this.etermUsername +
        "&device=" +
        this.deviceId;
      const url = APP_FLIGHT_PATH + "/tprs/download?" + params;
      window.open(url);
    },
  },
};
</script>
